package com.moon.game.client;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.moon.game.clazz.PBMessageProto.PBMessage;
import com.moon.game.command.RequestSession;
import com.moon.game.server.SessionPool;

class UdpClientHandler extends SimpleChannelUpstreamHandler {

    private static final Logger log = Logger.getLogger(UdpClientHandler.class);

    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

        PBMessage response = (PBMessage) e.getMessage();
        if (response.getSessionId() == 0)
            return;
        log.info("server response,status=" + response.getStatus() + ",sessionId=" + response.getSessionId() + ",cmd=" + response.getCmd());
        // 超时重发等情况需要校验状态是否和当前session中的status一致
        RequestSession reqSession = SessionPool.inst.getReqSession(response.getSessionId());
        if (reqSession != null && reqSession.getStatus() == response.getStatus()) {
            log.info("server response and push data. sessionId=" + response.getSessionId());
            SessionPool.UniData newReq = new SessionPool.UniData(SessionPool.UniData.FROM_NET, response.getSessionId(), response);
            SessionPool.inst.addData(newReq);
        }

    }

    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        log.error("server data exception,session", e.getCause());
    }

}